<#include "../include/header.html">

<script type="text/javascript">
    var viewModel = Hap.createGridViewModel("#grid", {
        model: {},
        newResource: function (e) {
            var win = $('#newWin').kendoWindow({
                iframe: true,
                draggable: false,
                content: '${base.contextPath}/demo/om_order_lines.html',
            }).data('kendoWindow');
            win.title('<@spring.message "hap.new"/>');
            win.maximize().open();
        },
        exportFunc: function (e) {
            var companyId = viewModel.model.companyId;
            var customerId = viewModel.model.customerId;
            var inventoryItemId = viewModel.model.inventoryItemId;
            var orderNumber = viewModel.model.orderNumber;
            var orderStatus = viewModel.model.orderStatus;
            $.ajax({
                type : "POST",
                url: "${base.contextPath}/hap/om/order/headers/selectExcelData",
                data: {
                    "companyId": companyId,
                    "customerId": customerId,
                    "inventoryItemId": inventoryItemId,
                    "orderNumber": orderNumber,
                    "orderStatus": orderStatus,
                },
                dataType: 'json',
                async: true,
                success: function(data) {
                    var originData = data.rows;
                    excelData(originData);
                }
            });

        },


    });
</script>
<body>
<script src="${base.contextPath}/common/code?orderStatusData=HAP_OM_ORDER_STATUS" type="text/javascript"></script>
<div id="page-content">
    <div id="newWin" style="display: none"></div>
    <div class="panel" id="query-form" style="padding: 0px;border:none;box-shadow: none;">
        <form class="form-horizontal" id="myForm">
            <div class="panel-body">
                <div class="row">
                    <!--公司名称 LOV-->
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label"><@spring.message
                                "hscs.assess.om_order_headers.companyname"/></label>
                            <div class="col-xs-8">
                                <input id="companyName" type="text" style="width:150px;margin-right:5px;"
                                       data-bind="value:model.companyId,text:model.companyName">
                                <script>
                                    $("#companyName").kendoLov($.extend(${lovProvider.getLov(base.contextPath, base.locale, "HAP_ORG_COMPANY_NAME")}, {
                                        select: function () {
                                            viewModel.model.set('customerId', null);
                                        },
                                        change: function () {
                                            viewModel.model.set('customerId', null);
                                        }
                                    }));
                                </script>
                            </div>
                        </div>
                    </div>
                    <!--客户名称 LOV-->
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label"><@spring.message
                                "hscs.assess.om_order_headers.customername"/></label>
                            <div class="col-xs-8">
                                <input id="customerName" type="text" style="width:150px;margin-right:5px;"
                                       data-bind="value:model.customerId,text:model.customerName">
                                <script>

                                    $("#customerName").kendoLov($.extend(${lovProvider.getLov(base.contextPath, base.locale, "HAP_AR_CUSTOMER_NAME")}, {
                                        query: function (e) {
                                            var a = $("#companyName").val();//传入限制参数
                                            e.param['companyId'] = a;

                                        },
                                        select: function (e) {
                                        }
                                    }));
                                </script>
                            </div>
                        </div>
                    </div>
                    <!--销售订单号 文本框-->
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label"><@spring.message
                                "hscs.assess.om_order_headers.ordernumber"/></label>
                            <div class="col-xs-8">
                                <input id="orderNumber" type="text" data-role="maskedtextbox"
                                       style="float:left;width:150px;margin-right:5px;"
                                       data-bind="value:model.orderNumber"
                                       class="k-textbox">
                            </div>

                        </div>
                    </div>
                </div>
                <div class="row">
                    <!--物料 LOV-->
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label"><@spring.message
                                "hscs.assess.om_order_headers.itemdescription"/></label>
                            <div class="col-xs-8">
                                <input id="itemDescription" type="text" style="width:150px;margin-right:5px;"
                                       data-bind="value:model.inventoryItemId,text:model.itemDescription">
                            </div>
                            <script>
                                $("#itemDescription").kendoLov($.extend(${lovProvider.getLov(base.contextPath, base.locale, "HAP_INV_INVENTORY_ITEMS_ITEM_NAME")}, {}))
                            </script>
                        </div>
                    </div>
                    <!--订单状态 下拉框-->
                    <div class="col-xs-4">
                        <div class="form-group">
                            <label class="col-md-4 control-label"><@spring.message
                                "hscs.assess.om_order_headers.orderstatus"/></label>
                            <div class="col-xs-8">
                                <input id="orderStatus" required type="text" style="width:150px;margin-right:5px;"
                                       data-bind="value:model.orderStatus">
                            </div>
                            <script>
                                $("#orderStatus").kendoComboBox({
                                    dataSource: orderStatusData,
                                    valuePrimitive: true,
                                    dataTextField: "meaning",
                                    dataValueField: "value"
                                });
                            </script>
                        </div>
                    </div>
                    <div class="col-xs-4">
                    </div>
                </div>
                <div class="row ">
                    <div class="col-xs-4">
                        <span class="btn btn-primary k-grid-add pull-left" style="float:left;margin-right:5px;"
                              data-bind="click:newResource"><@spring.message "hap.new"/></span>
                        <span class="btn btn-primary k-grid-reset pull-left" data-bind="click:reset" style="float:left;"><@spring.message "hap.reset"/></span>
                        <span class="btn btn-primary pull-left" style="float:left;margin-right:5px;margin-left:5px;"
                              data-bind="click:exportFunc"><@spring.message "hap.exportexcel"/></span>
                    </div>
                    <div class="col-xs-4"></div>
                    <div class="col-xs-4">
                        <span class="btn btn-default pull-right" type="button" data-bind="click:reset"><i
                                class="fa fa-eraser"
                                style="margin-right: 3px;"></i><@spring.message "hap.reset"/></span>
                        <span class="btn btn-primary pull-right" onclick="queryHeaderByForm()" type="submit"
                              style="margin-right: 3px;"><i
                                class="fa fa-search"></i><@spring.message "hap.query"/></span>
                        <div style="clear:both"></div>
                    </div>
                </div>

            </div>
        </form>
    </div>
    <script>kendo.bind($('#query-form'), viewModel);</script>

    <div style="clear:both">
        <div id="grid"></div>
    </div>
</div>

<script type="text/javascript">
    Hap.initEnterQuery('#query-form', viewModel.query);
    var BaseUrl = _basePath;
    dataSource = new kendo.data.DataSource({
        transport: {
            read: {
                url: BaseUrl + "/hap/om/order/headers/queryOrderHeaders",
                type: "POST",
                dataType: "json"
            },
            update: {
                url: BaseUrl + "/hap/om/order/headers/submit",
                type: "POST",
                contentType: "application/json"
            },
            destroy: {
                url: BaseUrl + "/hap/om/order/headers/remove",
                type: "POST",
                contentType: "application/json"
            },
            create: {
                url: BaseUrl + "/hap/om/order/headers/submit",
                type: "POST",
                contentType: "application/json"
            },
            parameterMap: function (options, type) {
                if (type !== "read" && options.models) {
                    var datas = Hap.prepareSubmitParameter(options, type)
                    return kendo.stringify(datas);
                } else if (type === "read") {
                    return Hap.prepareQueryParameter(viewModel.model.toJSON(), options)
                }
            }
        },
        batch: true,
        serverPaging: false,
        pageSize: 10,
        schema: {
            data: 'rows',
            total: 'total',
            model: {
                id: "headerId",
                fields: {
                    orderNumber:{

                    }

                }
            }
        }
    });

    $("#grid").kendoGrid({
        dataSource: dataSource,
        resizable: true,
        scrollable: true,
        navigatable: false,
        sortable : true, //可排序
        selectable: 'multiple, rowbox',
        dataBound: function () {
            if (parent.autoResizeIframe) {
                parent.autoResizeIframe('${RequestParameters.functionCode!}')
            }
        },
        pageable: {
            pageSizes: [5, 10, 20, 50],
            refresh: true,
            buttonCount: 5
        },
        columns: [
            {
                field: "",
                title: '<@spring.message "操作"/>',
                width: 120,
                template: function (dataItem) {
                    var html = '<a class="k-grid-column-view" href="javascript:void(0)" onclick="view(' + dataItem.headerId + ')" style="text-decoration: underline; color: blue; cursor: pointer;float: left; margin-right: 10px;"><@spring.message "hap.view"/></a>' +
                        '<a class="k-grid-column-edit" href="javascript:void(0)" onclick="edit(' + dataItem.headerId + ')" style="text-decoration: underline; color: blue; cursor: pointer;float: left; margin-right: 10px;"><@spring.message "hap.edit"/></a>';
                    return html;
                }

            },

            {
                field: "orderNumber",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.ordernumber"/>',
                width: 120,

            },
            {
                field: "companyName",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.companyName"/>',
                width: 120
            },
            {
                field: "customerName",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.customerName"/>',
                width: 120
            },
            {
                field: "orderDate",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.orderdate"/>',
                width: 120
            },
            {
                field: "orderStatus",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.orderstatus"/>',
                width: 120,
                template: function (dataItem) {
                    var v = dataItem.orderStatus;
                    $.each(orderStatusData, function (i, n) {
                        if ((n.value || '')== (v || '')) {
                            v = n.meaning;
                            return false;
                        }
                    });
                    return v;
                },
                editor: function (container, options) {
                    $('<input id="' + options.filed + '" required name="' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            dataTextField: "meaning",
                            dataValueField: "value",
                            valuePrimitive: true,
                            dataSource: orderStatusData,

                        });
                }
            },
            {
                field: " orderTotalPrices",
                title: '<@spring.message "hscs.assess.om_order_headers.grid.orderTotalPrices"/>',
                width: 120
            },
        ],
        editable: false
    });



    //点击查看按钮
    function view(headerId) {
        var win = $("#newWin").kendoWindow({
            iframe: true,
            draggable: false,
            content: '${base.contextPath}/demo/om_order_lines.html?queryFlag=2&headerId=' + headerId,
        }).data('kendoWindow');
        win.title('<@spring.message "hap.view"/>');
        win.maximize().open();
    }

    //点击编辑按钮
    function edit(headerId) {
        var win = $("#newWin").kendoWindow({
            iframe: true,
            draggable: false,
            content: '${base.contextPath}/demo/om_order_lines.html?queryFlag=1&headerId=' + headerId,
        }).data('kendoWindow');
        win.title('<@spring.message "hap.edit"/>');
        win.maximize().open();

    }


    function queryHeaderByForm() {
        var companyId = viewModel.model.companyId;
        var customerId = viewModel.model.customerId;
        var inventoryItemId = viewModel.model.inventoryItemId;
        var orderNumber = viewModel.model.orderNumber;
        var orderStatus = viewModel.model.orderStatus;

        $.ajax({
            url: '/hap/om/order/headers/queryOrderHeaders',
            type: 'POST',
            async: true,
            data: {
                "companyId": companyId,
                "customerId": customerId,
                "inventoryItemId": inventoryItemId,
                "orderNumber": orderNumber,
                "orderStatus": orderStatus,

            },
            dataType: 'json',

            success: function (data) {
                console.log(data);
                $('#grid').data('kendoGrid').dataSource.read();

            },
            error: function () {
                console.log('错误')

            },

        })

    }
    //点击销售订单号按钮
    function viewOrderLines(headerId) {
        var win = $("#newWin").kendoWindow({
            iframe: true,
            draggable: false,
            content: '${base.contextPath}/demo/om_order_lines.html?queryFlag=1&headerId=' + headerId,
        }).data('kendoWindow');
        win.title('<@spring.message "hap.view"/>');
        win.maximize().open();
    }

    //导出
    function excelData(originData) {

        if (originData.length > 0){ //如果有选中数据则导出数据
            for (var i in originData){

                originData[i].orderDate = kendo.toString(kendo.parseDate(originData[i].orderDate), "yyyy-MM-dd");

                var v = originData[i].orderStatus;
                if(v == "NEW"){
                    originData[i].orderStatus = "新建";
                }else if(v == "SUBMITED"){
                    originData[i].orderStatus = "已提交";
                }else if(v == "APPROVED"){
                    originData[i].orderStatus = "已审批";
                }else{
                    originData[i].orderStatus = "已拒绝";
                }
            }
        }else {
            return;
        }

        /*/!**
         * 2.设置excel格式与内容
         *!/

         /!**
         * 2.1设置excel表格标题
         *!/*/
        var excelTitles = [
            '<@spring.message "hscs.assess.om_order_headers.ordernumber"/>',
            '<@spring.message "hscs.assess.om_order_headers.companyname"/>',
            '<@spring.message "hscs.assess.om_order_headers.customername"/>',
            '<@spring.message "hscs.assess.om_order_lines.orderdate"/>',
            '<@spring.message "hscs.assess.om_order_headers.orderstatus"/>',
            '<@spring.message "hscs.assess.om_order_lines.grid.itemcode"/>',
            '<@spring.message "hscs.assess.om_order_lines.grid.itemdescription"/>',
            '<@spring.message "hscs.assess.om_order_lines.grid.orderquantityuom"/>',
            '<@spring.message "hscs.assess.om_order_lines.grid.unitsellingprice"/>',
            '<@spring.message "hscs.assess.om_order_lines.ordertotalprices"/>',
        ];
        //标题数组
        var excelHeader = [];
        for(var i in excelTitles){
            excelHeader.push({
                value: excelTitles[i],                    //标题文字
                background: '#92cddc',                 //标题背景颜色
                color: '#000',                         //标题字体颜色
                textAlign: 'center',                     //文字水平对齐方式
                verticalAlign: 'center',                  //文字竖直对齐方式
                borderLeft: {size: 1 ,color:"#ddd"},       //左边框大小及颜色
                borderRight: {size: 1 ,color:"#ddd"},      //右边框大小及颜色
                borderBottom: { size: 1 ,color:"#ddd"},   //下边框大小及颜色
                borderTop: { size: 1 ,color:"#ddd"},      //上边框大小及颜色
            })
        }

        /*/!**
         * 2.2设置最终导出数据
         *!/*/
        //最终导出数据
        var excelData = [];
        //2.2.1将标题添加至导出数据
        excelData.push({
            cells: excelHeader
        });
        //2.2.2将源数据添加至导出数据
        for(var i=0;i < originData.length;i++){
            excelData.push({
                cells: [
                    { value: originData[i].orderNumber, borderBottom: { size: 1 ,color:"#ddd"},borderRight: { size: 1 ,color:"#ddd"},verticalAlign: 'center', textAlign: 'center',background: '#ff9' },
                    { value: originData[i].companyName, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].customerName, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].orderDate, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].orderStatus, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].itemCode, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].itemDescription, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].orderdQuantity, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].unitSellingPrice, verticalAlign: 'center', textAlign: 'center'},
                    { value: originData[i].orderTotalPrices, verticalAlign: 'center', textAlign: 'center'},
                ],
            });
        }
        //2.2.3设置列宽度与样式
        var columns = [];
        for(var i = 0;i < excelTitles.length;i++){
            columns.push({ width: 150 });
        }

        /*/!**
         * 3.配置导出excel sheets,格式与文件名
         *!/*/
        var workbook = new kendo.ooxml.Workbook({
            date: new Date(),
            sheets: [ // sheet数组，如需导出多个sheet在此完成
                {
                    name: '<@spring.message "hscs.assess.excel.sheet.name"/>',       //sheet 名称
                    frozenRows: 1,         //冻结第一行
                    frozenColumns: 1,      //冻结第一列
                    columns: columns,      //列
                    rows: excelData        //数据
                }
            ]
        });

        //设置文件名
        kendo.saveAs({
            dataURI: workbook.toDataURL(), //数据源
            fileName: '<@spring.message "hscs.assess.excel.name"/>' //文件名
        });
    }
</script>
</body>
</html>